package com.hcg.multidatasourceofanno2.config.datasource;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Slf4j
//@Order(-1)  同 getOrder() 方法：保证该AOP在@Transactional之前执行
public class DynamicDataSourceAspect implements Ordered {
//    private Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);

    public DynamicDataSourceAspect() {
    }

    @Before("@annotation(targetDataSource)")
    public void changeDataSource(JoinPoint joinPoint, TargetDataSource targetDataSource) {
        DynamicDataSource.setDatasource(targetDataSource.value());
        if (this.log.isDebugEnabled()) {
            this.log.debug("dataSource change to {}", targetDataSource.value());
        }

    }

    @After("@annotation(targetDataSource)")
    public void releaseDataSource(JoinPoint joinPoint, TargetDataSource targetDataSource) {
        DynamicDataSource.clearDatasource();
        if (this.log.isDebugEnabled()) {
            this.log.debug("clear dataSource after.");
        }

    }

    @AfterThrowing("@annotation(targetDataSource)")
    public void releaseDataSourceAfterThrowing(JoinPoint joinPoint, TargetDataSource targetDataSource) {
        DynamicDataSource.clearDatasource();
        if (this.log.isDebugEnabled()) {
            this.log.debug("clear dataSource after throwing.");
        }

    }

    public int getOrder() {
        return -2147483647;
    }
}

